import store from '../store'
import { Message } from 'element-ui'
import { local, session } from '../utils/jcore/storage'
import { findNodeDfs } from '@/utils/jcore/tree'
import { flatPidToTree } from '@/utils/tools/common'
import { getSysMenuTree } from '../apiList/apiWorkCZR'
import { adminViewTokenLogin } from '../apiList/loginAuth'

/**
 * 路由相关接口
 */

// 获取菜单列表
export async function getterMenusTree(userInfo) {
  let res = await getSysMenuTree(userInfo.sysRoleCodes)
  let list = res.filter((n) => n.sysType === 0)
  let menus = flatPidToTree(list)
  local.set('userInfo', userInfo)
  if (!menus) {
    Message.error('当前账户菜单权限不足')
    throw new Error({ code: 1, msg: '获取菜单失败' })
  }
  const adminMenu = findNodeDfs(menus, (node) => {
    return node.code === 'admin'
  })
  if (!adminMenu) {
    Message.error('当前账户没有管理员权限')
    throw new Error({ code: 1, msg: '管理员菜单获取失败' })
  }
  return adminMenu.children
}

// 用户免登录
export async function viewTokenLogin(token) {
  let res = await adminViewTokenLogin({ token })
  if (!res) {
    Message.error('登录失败')
    throw new Error({ code: 5, msg: '没有数据直接跳转登录页' })
  }
  let firstUserInfo = res.data[0]
  session.set('token', token)
  local.set('dutylist', res)
  local.set('userInfo', firstUserInfo)
  store.dispatch('app/setUserInfo', firstUserInfo)
}
